// pages/classify/classify.js
const app = getApp()
const pool = new Map()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        status: 'DEFAULT',
        sort: 3,
        loading: false,
        num: 1,
        category: [],
        sortTab: [{
                name: '综合排序',
                status: 'DEFAULT'
            },
            {
                name: '按价格',
                status: 'PRICE'
            },
            {
                name: '销量',
                status: 'SELL'
            },
        ],
        f_default_index:0
    },
    onLoad: function(options) {
        wx.showLoading({
            title: '加载中...',
        })
    },
    onShow() {
        let cid = wx.getStorageSync('cid')
        this.setData({
            cid,
        })
        this.loadCategory()
    },
    loadCategory() {
        app.http.get('goods/category-list', {
            data: {
                cid: this.data.cid
            }
        }).then(res => {
            this.setData({
                category: res.data,
            })
            this.menuClick({
                currentTarget: {
                    dataset: {
                        id: this.data.category[this.data.f_default_index].id,
                        type: this.data.category[this.data.f_default_index].type,
                        index: this.data.f_default_index
                    }
                }
            })
            wx.hideLoading()
        }).catch(err => {
            app.wxToast.error(err.message);
        })
    },

    tab() {
        if (!pool.has(this.data.child_id)) {
            pool.set(this.data.child_id, {
                page: 1,
                nextPage: true,
                loading: false,
                list: []
            })
        }
        return pool.get(this.data.child_id)
    },
    loadGoods() {
        const tab = this.tab()
        if (tab.loading || !tab.nextPage) {
            wx.stopPullDownRefresh()
            return
        }
        this.setData({
            loading: true
        })
        let location = wx.getStorageSync('location')
        app.http.get("goods/list", {
            data: {
                // cid: this.data.cid ? this.data.cid : 0,
                // site_id: this.data.siteInfo ? this.data.siteInfo.id : 0,
                cid: this.data.cid,
                // id_type: this.data.cid ? 1 : this.data.siteInfo.id ? 2 : null,
                page: tab.page,
                category_id: this.data.child_id,
                sort: this.data.status,
                sort_type: this.data.sort,
                // location: location.lng + ',' + location.lat,
            }
        }).then(res => {
            tab.page++
            tab.loading = false
            tab.nextPage = res.data.nextStatus
            // .map(o => {
            //     o.pre_obj = this.time_range(o.group_time.group_start_time, o.group_time.group_end_time)
            //     return o
            // })
            tab.list.push(...res.data.list)
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
        }).catch(res => {
            this.setData({
                loading: false,
            })
        })
    },
    /**
     * 核销商品
     */
    writeOff() {
        const tab = this.tab()
        if (tab.loading || !tab.nextPage) {
            wx.stopPullDownRefresh()
            return
        }
        this.setData({
            loading: true
        })
        let location = wx.getStorageSync('location')
        app.http.get('hx-goods/site-goods-index', {
            data: {
                cid: this.data.cid,
                page: tab.page,
                category_id: this.data.child_id,
                location: location.lng + ',' + location.lat,
                sort: this.data.status,
                sort_type: this.data.sort
            }
        }).then(res => {
            tab.page++
                tab.loading = false
            tab.nextPage = res.data.next_page
            tab.list.push(...res.data.list.map(o => {
                let now_time = new Date().getTime()
                o.isStart = o.rush_start_at <= 0 || (o.rush_start_at * 1000) <= now_time
                o.isEnd = o.rush_end_at > 0 && (o.rush_end_at * 1000) <= now_time
                return o
            }))
            this.setData(tab)
            wx.stopPullDownRefresh()
        }).catch(err => {
            this.setData({
                loading: false,
            })
        })
    },
    loadMore() {
        this.data.child_type == '11' ? this.loadGoods() : this.writeOff()
    },
    loadList() {
        const tab = this.tab()
        tab.page = 1
        tab.loading = false
        tab.nextPage = true
        tab.list = []
        this.setData(tab)
        this.data.child_type == '11' ? this.loadGoods() : this.writeOff()
    },
    clickChildCategory(evt) {
        let child_id = evt.currentTarget.dataset.id
        let child_type = evt.currentTarget.dataset.type
        this.setData({
            child_id,
            child_type,
        })
        this.loadList()
    },
    menuClick: function(evt) {
        let category_id = evt.currentTarget.dataset.id
        let index = evt.currentTarget.dataset.index
        let category_type = evt.currentTarget.dataset.type
        let currentCate = this.data.category.find(o => o.id == category_id)
        this.setData({
            category_id,
            category_type,
            f_default_index:index,
            childCategory: currentCate.children.length != 0 ? [{
                id: category_id,
                type: category_type,
                name: '全部'
            }].concat(currentCate.children) : []
        })
        this.clickChildCategory({
            currentTarget: {
                dataset: {
                    id: category_id,
                    type: category_type
                }
            }
        })
    },
    //加入购物车
    joinCart(evt) {
        let {
            goodsid,
            index
        } = evt.currentTarget.dataset
        let specList = this.data.list[index].sku
        this.setData({
            specList,
            showSpec: specList.length!=0 ? true : false,
            currentGoodsIndex: index
        });
		!this.data.showSpec && this.submitSpec({
            currentTarget: {
                dataset: {
                    goodsid: goodsid,
                }
            }
        })

    },
    closeSpec() {
        this.setData({
            showSpec: false
        })
    },
    specClick(evt) {
        this.setData({
            currentSpec: evt.currentTarget.dataset.index
        })
    },
    submitSpec(evt) {
        let goods_id = evt.currentTarget.dataset.goodsid
        let {
            num = 1, cid = 0 , cartNum = 0, currentSpec = null, specList = [], currentGoods = {}, currentGoodsIndex = 0
        } = this.data
        let cart_quantity = this.data.list[currentGoodsIndex].cart_quantity
        if (specList != 0 && currentSpec == null) {
            wx.showToast({
                icon: 'none',
                title: '请选择规格',
            })
            return
        }

        // let siteInfo = wx.getStorageSync('siteInfo')
        let params = {
            goods_id: specList.length != 0 ? specList[currentSpec].goods_id : goods_id,
            quantity: num,
            sku_id: specList.length != 0 ? specList[currentSpec].id : 0,
            // cid: cid,
            type: 1,
            // site_id: siteInfo ? siteInfo.id : 0
        }
        wx.showLoading({
            title: '请稍等...',
        })
        app.addToCart(params).then(res => {
            wx.hideLoading()
            // cartNum++`
            cart_quantity++
            this.setData({
                // cartNum,
                showSpec: false,
                currentSpec: null,
                specList: [],
                [`list[${currentGoodsIndex}].cart_quantity`]: cart_quantity
            })
            // app.setTabCart(this.data.cartNum)
            wx.showToast({
                icon: 'none',
                title: '添加购物车成功,等你来买',
            })
        }).catch(err => {
            wx.hideLoading()
            this.setData({
                showSpec: false,
                currentSpec: null,
                specList: [],
            })
        })
        // app.http.post('shopping-cart/add-shopping-cart', {
        //     data: {
        //         goodsId: specList.length != 0 ? specList[currentSpec].goods_id : goods_id,
        //         quantity: num,
        //         skuId: specList.length != 0 ? specList[currentSpec].id : '',
        //         cid: cid,
        //     }
        // }).then(res => {
        //     wx.hideLoading()
        //     if (res.data.status != 1) {
        //         wx.showModal({
        //             title: '提示',
        //             content: res.data.msg,
        //             showCancel: false,
        //             confirmColor: '#ff5400'
        //         })
        //         this.setData({
        //             showSpec: false,
        //             currentSpec: null,
        //             specList: [],
        //         })
        //         return
        //     }
        //     cartNum++
        //     cart_quantity++
        //     this.setData({
        //         cartNum,
        //         showSpec: false,
        //         currentSpec: null,
        //         specList: [],
        //         [`list[${currentGoodsIndex}].cart_quantity`]: cart_quantity
        //     })
        //     app.setTabCart(this.data.cartNum)
        //     wx.showToast({
        //         icon: 'none',
        //         title: '添加购物车成功,等你来买',
        //     })
        // })
    },
    bindStatus(e) {
        let sort = this.data.sort //当前sort
        let status = e.currentTarget.dataset.status
        if (sort == 4) { //如果为升序，设置为降序
            sort = 3
        } else {
            sort = 4
        }
        this.setData({
            status,
            sort,
        })

        this.loadList()
    },
    toDetail(evt) {
        let id = evt.currentTarget.dataset.id
        this.setData({
            isClose: false,
            compareCid: this.data.cid
        })
        wx.navigateTo({
            url: '../goods/detail?cid=' + this.data.cid + '&goods_id=' + id
        })
    },
    onUnload() {
        setTimeout(() => {
            this.setData({
                isClose: true
            })
        }, 200)
    },
    onHide() {
        if (this.data.isClose) {
            console.log('重新打开')
        }
    },
})